package com.trs.publish.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.trs.publish.domain.User;
import com.trs.publish.service.UserService;

/**
 * 密码管理
 * @author jia.haihong
 *
 */

@Controller
public class PasswordController{ 
	
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired 
	private UserService userService;
	
	@RequestMapping(value = "/toPassword")
    public String toUser() {
        return "password/detail";
    }  
	
	/**
	 * 更新/新增用户
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/password", method = RequestMethod.PUT,produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object updatePassword(@RequestBody User user, HttpServletRequest request) {
		User sessionuser = (User) request.getSession().getAttribute("user");
		Map<String, Object> map = new HashMap<String, Object>();
		
		long id = sessionuser.getId();
		String password = user.getPassword();
		//password加密
		BCryptPasswordEncoder encode = new BCryptPasswordEncoder(4);  
	    String hashPass = encode.encode(password);
	    
	    //更新用户
		User u = new User();
		u.setId(id);
		u.setPassword(hashPass);
		u.setLastactivetime(new Date());
		userService.update(u);
		map.put("message","更新成功");
		return map;
	}
}

